$(function () {

    // ------some Tool functions (pure function)
    $('title').html("会议室预约");

    var user = $("#userUser").val();
    curRoomId = $("#room_id").val();

    $('#btn-reservation').attr('class', 'navbar-btn btn btn-default btn-active');

    // $('#room-dropdown').html(btnRooms[Number(curRoomId - 1)]);
    // console.log(' --- room_id ---- ', curRoomId);
    // $('#room-dropdown').text('电信学院第二会议室')

    //判断登录用户是否是管理员，如果是，则显示管理员页面
    isAdaminPage();

    //设置是否是管理员页面
    function isAdaminPage() {
        console.log('user : ' + user);
        $.post('/account-check', {'user': user}, function (result) {
            console.log('result : ' + result.id);
            if (result.id === 1) { //管理员页面
                $('#manage-reservation').css('visibility', 'visible');
                // $('#btn-manage-account').show();
                // $('#manage-reservation').show();
            } else {//普通用户和特殊用户
                $('#manage-reservation').css('visibility', 'hidden');
                // $('#manage-reservation').hide();
            }
        });
    }


    //Warning: dataBase's data is too many items, some(e.g _id) will cover fullCalendar's item,
    //and cause to 'removeEvents' can't run completely'
    //and convert 'id'(int) to (string)
    function toTidy(data, items) {

        var now = moment();

        console.log('moment: ' + moment);

        items = items || ['id', 'title', 'inc_name', 'allDay', 'start', 'end', 'room_id', 'user', 'status'];
        var tidy = [];

        data.forEach(function (element, index) {
            tidy[index] = {};
            items.forEach(function (item) {
                tidy[index][item] = element[item];

                if (item == 'title') {
                    tidy[index][item] = element['inc_name'] + " - " + element['title'];
                }
                if (item == 'status') {
                    var end = moment.unix(element['end']);
                    //使每个预约以不同的颜色显示， 1， 2， 3 , 4, 5
                    if (now > end) {
                        tidy[index]['color'] = colorStatus[3].color;
                        //如果预约已经完成， 则加上删除线
                        tidy[index]['className'] = 'strikethrough';
                        tidy[index]['textColor'] = '#fff';
                        // tidy[index]['textColor'] = '#b0bec5';
                    } else {
                        tidy[index]['color'] = colorStatus[Number(element[item]) - 1].color;
                    }
                }

                if (item == 'start') {
                    var start = moment.unix(element[item]);
                    tidy[index][item] = start.format();
                }

                if (item == 'end') {
                    var end = moment.unix(element[item]);
                    tidy[index][item] = end.format();
                }

            })
        });

        return tidy;
    }


    //
    function toSerialize(data) {
        var str = '';
        for (var index in data) {
            str = str + index + '=' + data[index].val() + '&';
        }
        return str;
    }


    //初始化日历
    var calendar = $('#calendar').fullCalendar({
        theme: true,
        header: {
            left: 'prev,next today',
            center: 'title',
            right: 'month,agendaWeek,agendaDay,listMonth'
        },
        defaultView: 'agendaWeek',
        navLinks: false, // can click day/week names to navigate views
        eventLimit: true, // allow "more" link when too many events
        editable: false,
        startEditable: false,
        durationEditable: false,
        dragScroll: false,
        disableDragging: false,
        diableResizing: false,

        //点击跳转到当天
        dayClick: function (date, jsEvent, view) {
            $(this).css('background-color', '#2F79B9');
            // change the day's background color just for fun
            calendar.fullCalendar('gotoDate', date);
            calendar.fullCalendar('changeView', "agendaDay");
        },

        // height: 650,
        businessHours: {
            start: '8:00',
            end: '22:00'
        },
        locale: 'zh-cn',

        eventOverlap: function (stillEvent, movingEvent) {
            return true;
        },

        events: function (start, end, timezone, callback) {
            //默认加载第一会议室列表
            $.get('/reservation-get', {roomId: curRoomId}, function (result) {
                if (result.id === 1) {
                    var newEvents = toTidy(result.data, ['id', 'title', 'inc_name', 'allDay', 'start', 'end', 'room_id', 'status']);

                    $.get('/weathers-get', function (weatherList) {
                        weatherList.forEach(function (weather) {
                            weather['allDay'] = true;
                            weather['editable'] = false;
                            weather['disableDragging'] = false;
                            weather['overlap'] = false;
                            weather['className'] = 'weather';
                        });

                        var list = newEvents.concat(weatherList);
                        callback(list);
                    });
                }
            });
        },

        eventClick: function (calEvent, jsEvent, view) {
            var id = calEvent.id + '';
            if (!id.startsWith('day')) { //如果点击天气，不跳转
                $(this).css('border-color', 'red');
                //查看页面
                $(location).attr('href', '/reservation-add?id=' + id + '&update=' + 1);
            }
        }
    });


    //清除选中的tap
    function clearAllMark() {
        for (i = 0; i < roomIds.length; i++) {
            $(roomIds[i]).attr('class', '');

        }
    }

    function setCurRoomMark() {
        clearAllMark();
        $(roomIds[Number(curRoomId - 1)]).attr('class', 'active');
    }

    setCurRoomMark();

    // $(document).ready(function () {

    //点击预约申请
    $("#make-reservation").click(function () {
        //跳转到添加页面
        $(location).attr('href', '/reservation-add?roomId=' + curRoomId + '&update=' + 3);
    });

    //点击我的预约
    $("#my-reservation").click(function () {
        window.location.href = '/reservation-my';
        // $(location).attr('href', '/reservation-my?user=' + user);
    });

    //点击预约管理
    $("#manage-reservation").click(function () {
        // var user = $("#userUser").val();
        // $(location).attr('href', '/reservation-manage?user=' + user);
        window.location.href = '/reservation-manage';
    });

    $("#room1").click(function () {
        curRoomId = '1';

        // 然后要重新加载预约列表，显示
        loadReservation(curRoomId);
    });


    $("#room2").click(function () {
        curRoomId = '2';
        loadReservation(curRoomId);
    });

    $("#room3").click(function () {
        curRoomId = '3';
        loadReservation(curRoomId);
    });

    $("#room4").click(function () {
        curRoomId = '4';
        loadReservation(curRoomId);
    });

    //加载不同会议室的预约列表
    function loadReservation(curRoomdId) {
        window.location.href = '/reservation?roomId=' + curRoomdId;
    }

    $('#common-question').click(function () {
        bootbox.alert({
            size: "small",
            title: "常见问题",
            message: questions

        });
        $('.modal-footer .btn')[1].innerText = '返回';
    });

    $('#reservation-flow').click(function () {
        bootbox.alert({
            size: "large",
            title: "预约流程图",
            message: flow

        });
        $('.modal-footer .btn')[1].innerText = '返回';
    });

});